package com.example.community.controller.interceptor;

import com.example.community.entity.LoginTicket;
import com.example.community.entity.User;
import com.example.community.service.UserService;
import com.example.community.util.CookieUtil;
import com.example.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author: huang
 * @Date: 2021/9/18 21:19
 * @Description:
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    //在Controller之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从cookie中获取凭证。可能这一行为在别的地方也有用，所以我们写个类(CookieUtil)进行复用。
        String ticket = CookieUtil.getValue(request, "ticket");

        if (ticket != null) {
            //2.查询凭证，获取到凭证中的信息
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            //3.查询凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                //4.根据凭证查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                //5.在本次请求中持有用户。服务器同时处理多个请求可能会出现问题，我们写一个类里面有ThreadLocal进行线程隔离
                hostHolder.setUser(user);
                //构建用户认证结果，并存入SecurityContext，以便Security进行授权
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), userService.getAuthorities(user.getId())
                );
                //SecurityContext是通过SecurityContextHolder处理
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }
        return true;
    }

    //在模板之前调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //上一步中hostHolder类中我们存放了当前用户
        //从我们写的hostHolder类中获取当前用户
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null) {
            //我们把用户存入 ModelAndView 模板视图中
            modelAndView.addObject("loginUser", user);
        }

    }

    //模板执行完后，把user清除掉
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
        SecurityContextHolder.clearContext();
    }

}
